<template>
  <view class="password-input-group">
    <!-- #ifdef MP-WEIXIN -->
    <!-- 微信小程序环境：使用 password 属性 -->
    <input
      type="text"
      :password="!showPassword"
      :value="innerValue"
      :placeholder="placeholder"
      class="password-input"
      @input="handleInput"
      @focus="handleFocus"
      :focus="isFocused"
    />
    <!-- #endif -->
    
    <!-- #ifndef MP-WEIXIN -->
    <!-- 非微信小程序环境：使用 type 属性 -->
    <input
      :type="showPassword ? 'text' : 'password'"
      :value="innerValue"
      :placeholder="placeholder"
      class="password-input"
      @input="handleInput"
      @focus="handleFocus"
      :focus="isFocused"
    />
    <!-- #endif -->
    
    <!-- 切换按钮 -->
    <view class="toggle-btn" @click="togglePasswordVisibility">
      <text class="icon">{{ showPassword ? '👁️' : '👁️‍🗨️' }}</text>
    </view>
  </view>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue';

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: '请输入密码'
  }
});

const emit = defineEmits(['update:modelValue', 'toggle']);

const innerValue = ref(props.modelValue);
const showPassword = ref(false);
const isFocused = ref(false); // 控制焦点

// 处理输入事件
const handleInput = (e) => {
  innerValue.value = e.detail.value;
  emit('update:modelValue', innerValue.value);
};

// 切换密码可见性
const togglePasswordVisibility = async () => {
  // 先失去焦点
  isFocused.value = false;
  // 等待视图更新
  await nextTick();
  
  // 切换状态
  showPassword.value = !showPassword.value;
  emit('toggle');
  
  // 短暂延迟后重新聚焦
  setTimeout(() => {
    isFocused.value = true;
  }, 50);
};

// 处理聚焦事件
const handleFocus = () => {
  isFocused.value = true;
};

// 同步父组件的值
watch(() => props.modelValue, (newVal) => {
  if (newVal !== innerValue.value) {
    innerValue.value = newVal;
  }
});
</script>

<style scoped>
.password-input-group {
  position: relative;
  display: flex;
  align-items: center;
  width: 100%;
}
.password-input {
  flex: 1;
  width: 100%;
  padding-right: 80rpx;
  height: 100rpx;
  font-size: 32rpx;
  border-bottom: 1px solid #eee;
}
.toggle-btn {
  position: absolute;
  right: 20rpx;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2;
}
.icon {
  font-size: 34rpx;
}
</style>